package com.yoyo.itravel.web.controller;

import com.yoyo.itravel.bean.*;
import com.yoyo.itravel.constants.SightConstat;
import com.yoyo.itravel.exceptions.CityException;
import com.yoyo.itravel.exceptions.CountryException;
import com.yoyo.itravel.exceptions.ProvinceException;
import com.yoyo.itravel.exceptions.SightException;
import com.yoyo.itravel.service.*;
import com.yoyo.itravel.utils.FileUploadUtils;
import com.yoyo.itravel.utils.JSONUtils;
import com.yoyo.itravel.utils.StringUtils;
import jdk.nashorn.internal.ir.RuntimeNode;
import org.apache.ibatis.annotations.Param;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.Multipart;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.util.*;

/**
 * @author HZX
 * @Description 景点相关操作服务端
 * @date 2020/5/13 15:41
 */
@Controller
@RequestMapping("/sight")
public class SightController {

    @Autowired
    private ISightService sightService;
    @Autowired
    private ITicketTypeService ticketTypeService;
    @Autowired
    private IProvinceService provinceService;
    @Autowired
    private ICityService cityService;
    @Autowired
    private ICountryService countryService;

    /**
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     * @Description 通过景点id查询景点
     */
    @RequestMapping("/findSightBySightId")
    protected void findSightBySightId(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获得传过来的数据
        String sightId = request.getParameter("sightId");

        if (StringUtils.isEmpty(sightId)) {
            // 如果未传景点id，则跳转到404页面
            response.sendRedirect(request.getContextPath() + "/404.jsp");
            return;
        }

        // 构建RestInfo对象
        ResultInfo info = new ResultInfo();

        try {
            // 根据景点id，获得景点
            Sight sight = sightService.findSightBySightId(sightId);

            JSONUtils.writeValueToResponse(sight, response);
        } catch (SightException e) {
            e.printStackTrace();
            // 出现异常，将异常信息添加至info中
            info.setFlag(false);
            info.setErrorMsg(e.getMessage());
            // 将json数据写回客户端
            JSONUtils.writeValueToResponse(info, response);
        }
    }

    /**
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     * @Description 查找最热景点
     */
    @RequestMapping("/findHotestSight")
    protected void findHotestSight(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 构建RestInfo对象
        ResultInfo info = new ResultInfo();

        try {
            // 根据景点id，获得景点
            List<Sight> sellestSight = sightService.findSellestSight(SightConstat.TOP_SELLING);

            JSONUtils.writeValueToResponse(sellestSight, response);
        } catch (SightException e) {
            e.printStackTrace();
            // 出现异常，将异常信息添加至info中
            info.setFlag(false);
            info.setErrorMsg(e.getMessage());
            // 将json数据写回客户端
            JSONUtils.writeValueToResponse(info, response);
        }
    }

    /**
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     * @Description 查找最多收藏景点
     */
    @RequestMapping("/findCollectestSight")
    protected void findCollectestSight(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 构建RestInfo对象
        ResultInfo info = new ResultInfo();

        try {
            // 根据景点id，获得景点
            List<Sight> sellestSight = sightService.findCollectestSight(SightConstat.TOP_COLLECT);

            JSONUtils.writeValueToResponse(sellestSight, response);
        } catch (SightException e) {
            e.printStackTrace();
            // 出现异常，将异常信息添加至info中
            info.setFlag(false);
            info.setErrorMsg(e.getMessage());
            // 将json数据写回客户端
            JSONUtils.writeValueToResponse(info, response);
        }
    }

    /**
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     * @Description 根据条件查询分页显示景点信息
     */
    @RequestMapping("/queryPageByCondition")
    public void queryPageByCondition(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获得参数
        String currentPageStr = request.getParameter("currentPage");
        String pageSizeStr = request.getParameter("pageSize");
        String search = request.getParameter("search");
        String lowPrice = request.getParameter("lowPrice");
        String heightPrice = request.getParameter("heightPrice");

        // 获得传过来的数据
        String themeId = request.getParameter("themeId");
        String provinceId = request.getParameter("provinceId");
        String cityId = request.getParameter("cityId");

        // 构建RestInfo对象
        ResultInfo info = new ResultInfo();

        // 获得Cookie数组对象
        Cookie[] cookies = request.getCookies();

        // 处理参数
        int currentPage = 0; // 当前页码

        // 先从请求url中找当前页码，如果没有（为null），则到Cookie中去找，如果还没找到，则默认当前页码为1
        if (currentPageStr != null && currentPageStr.length() > 0) {
            currentPage = Integer.parseInt(currentPageStr);
        } else if (cookies != null && cookies.length != 0) {
            // 遍历cookies数组
            for (Cookie cookie : cookies) {
                if ("currentPage".equals(cookie.getName())) {
                    // 取出当前浏览的页码
                    currentPage = Integer.parseInt(cookie.getValue());
                }
            }
            // 再进一步判断，因为可能cookie中没有currentPage
            if (currentPage < 1) {
                currentPage = 1;
            }
        } else {
            // 如果没有传递参数，则默认为第一页
            currentPage = 1;
        }

//        // 构建Cookie对象--记录用户当前浏览页码
//        Cookie nowPageCookie = new Cookie("currentPage", currentPage + "");
//        // 添加Cookie对象至浏览器
//        response.addCookie(nowPageCookie);

        int pageSize = 0; // 每页显示条数

        if (pageSizeStr != null && pageSizeStr.length() > 0) {
            pageSize = Integer.parseInt(pageSizeStr);
        } else {
            // 如果没有传递参数，则默认显示10条数据
            pageSize = 10;
        }

        // 构建PageBean对象
        try {
            System.out.println(currentPage);
            PageBean<Sight> pageBean = sightService.queryCurrentPageByCondition(themeId, provinceId, cityId, currentPage, pageSize, search, lowPrice, heightPrice);

            JSONUtils.writeValueToResponse(pageBean, response);
        } catch (SightException e) {
            e.printStackTrace();
            // 出现异常，将异常信息添加至info中
            info.setFlag(false);
            info.setErrorMsg(e.getMessage());
            // 将json数据写回客户端
            JSONUtils.writeValueToResponse(info, response);
        }
    }

    /**
     * @Description 分页查询所有景点
     * @Param page
     * @Param size
     * @Param response
     * @Return void
     */
    @RequestMapping("/findAllSightByPage")
    @ResponseBody
    protected void findAllSightByPage(Integer page, @RequestParam("limit") Integer size, HttpServletResponse response) throws ServletException, IOException {
        // 参数合法性检测
        if (page == null || page < 1) {
            // 如果没有传起始页码，则默认为第一页
            page = 1;
        }
        if (size == null) {
            // 如果没有传递页码显示数据条数，则默认显示10条数据
            size = 10;
        }
        // 构建PageBean对象
        PageBean pageBean = new PageBean((page - 1) * size, size);
        // 构建JsonResult对象
        JsonResult jsonResult = new JsonResult();

        try {
            // 分页查询景点数据
            List<Sight> sights = sightService.findAllByPage(pageBean);
            // 查询景点数据的总条数
            Integer totalCount = sightService.findTotalCount();
            // 将景点数据和总条数设置到JsonResult对象中
            jsonResult.setData(sights);
            jsonResult.setCount(totalCount);
            JSONUtils.writeValueToResponse(jsonResult, response);
        } catch (SightException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description 修改景点的在售状态
     *
     * @Param request
     * @Param response
     * @Return void
     */
    @RequestMapping("/updateOnSellStatus")
    @ResponseBody
    protected void updateOnSellStatus(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获得景点id
        String sightId = request.getParameter("sightId");
        String newStatus = request.getParameter("newStatus");

        try {
            // 修改景点的在售状态
            sightService.updateOnSellStatusById(sightId, Integer.parseInt(newStatus));
            // 未出现异常，修改成功
        } catch (SightException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description 删除景点主题
     *
     * @Param request
     * @Param response
     * @Return void
     */
    @RequestMapping("/deleteSightTheme")
    @ResponseBody
    protected void deleteSightTheme(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获得景点id
        String sightId = request.getParameter("sightId");
        String themeId = request.getParameter("themeId");

        try {
            // 修改景点的在售状态
            sightService.deleteSightTheme(sightId, themeId);
            // 未出现异常，修改成功
        } catch (SightException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description 删除景点
     *
     * @Param request
     * @Param response
     * @Return void
     */
    @RequestMapping("/deleteSight")
    @ResponseBody
    protected void deleteSight(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获得景点id
        String sightId = request.getParameter("sightId");

        try {
            // 修改景点的在售状态
            sightService.deleteSight(sightId);
            // 未出现异常，修改成功
        } catch (SightException e) {
            e.printStackTrace();
        }
    }


    /**
     * @Description 添加景点
     *
     * @Param request
     * @Param response
     * @Return void
     */
    @RequestMapping("/addSight")
    @ResponseBody
    protected void addSight(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String sightName = request.getParameter("sightName");
        String introduce = request.getParameter("introduce");
        String orderNotice = request.getParameter("orderNotice");
        String province = request.getParameter("province");
        String city = request.getParameter("city");
        String openTime = request.getParameter("openTime");
        String county = request.getParameter("county");
        Integer onSellStatus = request.getParameter("onSellStatus") == null ? 0 : 1;
        String detailAddr = county + request.getParameter("detailAddr");
        String imgUrl = request.getParameter("imgUrl"); // 缩略图
        String imgUrls = request.getParameter("imgUrls");// 景点图片
        String sightCompany = request.getParameter("sightCompany");// 景点所属公司

        Sight sight = new Sight();

        sight.setSightName(sightName);
        sight.setOrderNotice(orderNotice);
        sight.setIntroduce(introduce);
        sight.setSightCompanyId(sightCompany);
        sight.setDetailAddr(detailAddr);
        sight.setIsOnSell(onSellStatus);
        sight.setOpenTime(openTime);
        sight.setSightCompanyId(sightCompany);
        // 将景点缩略图添加到景点对象
        sight.setSightImg(imgUrl);
        System.out.println(imgUrls);
        List<String> imgList = new ArrayList<String>();
        if (!StringUtils.isEmpty(imgUrls)) {
            imgList = Arrays.asList(imgUrls.split("&"));
        }
        for (String s : imgList) {
            System.out.println(s);
        }
        try {

            // 获得景点主题的总数量
            Integer totalCount = sightService.findTotalCount();
            // 构建list集合，用来存放景点主题id
            List<String> themeIdList = new ArrayList<String>();
            // 遍历，判断用户选择了多少个主题
            for (int i = 1; i <= totalCount; i++) {
                String sihgtTheme = request.getParameter("theme" + i);
                if (!StringUtils.isEmpty(sihgtTheme)) {
                    themeIdList.add(sihgtTheme);
                }
            }

            // 获得省份对象
            Province provinceObj = provinceService.findByName(province.trim());
            // 获得城市对象
            City cityObj = cityService.findByName(city.trim());
            if (provinceObj != null && cityObj != null) {
                // 通过省份id获得国家id
                Country country = countryService.findById(provinceObj.getCountryId());
                sight.setCountryId(country.getCountryId());
                sight.setProvinceId(provinceObj.getProvinceId());
                sight.setCityId(cityObj.getCityId());
            }

            // 添加景点图片
            sightService.addSight(sight, imgList, themeIdList);

        } catch (ProvinceException e) {
            e.printStackTrace();
        } catch (CityException e) {
            e.printStackTrace();
        } catch (SightException e) {
            e.printStackTrace();
        } catch (CountryException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description 上传景点缩略图
     *
     * @Param file
     * @Param request
     * @Return com.yoyo.itravel.bean.JsonResult
     */
    /* @RequestParam:如果不设置空值，是默认必须传值的。有时候没值，前台也无法传个空的值过来时，就会出现无法进方法的情况。*/
    @RequestMapping(value = "/uploadSightImg", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult uploadSightImg(@RequestParam(value = "file", required=true) MultipartFile file, HttpServletRequest request) {
        //如果文件内容不为空，则写入上传路径
        JsonResult jsonResult = new JsonResult();

        // 设置上传图片的保存路径
        String savePath = request.getServletContext().getRealPath("images/upload/sight");
        String targetSavePath = "D:\\StudyFile\\IntelliJ IDEA\\itravel\\itravel_web\\target\\itravel\\images\\upload\\sight";

        // 文件上传
        String imageUrl = null;
        try {
            // target中也上传一份
            FileUploadUtils.copy(file, targetSavePath, "");
            imageUrl = FileUploadUtils.transfer(file, savePath, "images/upload/sight");
            jsonResult.setCode(0);
            jsonResult.setMsg("上传成功！");
            jsonResult.setData(imageUrl);
        } catch (IOException e) {
            e.printStackTrace();
            jsonResult.setCode(1);
            jsonResult.setMsg("上传失败！");
        }

        // 返回
        return jsonResult;
    }

    @RequestMapping("/deleteBatch")
    @ResponseBody
    protected JsonResult deleteBatch(@RequestParam("ids[]") String[] ids, HttpServletRequest request) {
        JsonResult jsonResult = new JsonResult();

        try {
            sightService.deleteBatch(ids);
            jsonResult.setCode(0);
            jsonResult.setMsg("删除成功！");
        } catch (SightException e) {
            e.printStackTrace();
        }

        return jsonResult;
    }

}
